import { Application } from "mydog";
import {assert, DicObj} from "../util/util";
import { Table } from "./table";
import {I_playerEnter, Player} from "./player";
import {log} from "../util/log";


export class RoomMgr {
    private app: Application;
    private tables: DicObj<Table> = {};
    //优先桌子
    private sortTables:Array<Table> = [];
    private MAX_TABLE_COUNT:number;
    constructor(app: Application) {
        this.app = app;
        log.info("桌子数：%d,座位数: %d",this.app.serverInfo.tableCount,this.app.serverInfo.seatCount)
        assert(this.app.serverInfo.tableCount,"tableCount is null");
        this.MAX_TABLE_COUNT = this.app.serverInfo.tableCount;
        this.init();
        setInterval(this.update.bind(this), 100);
    }

    init(){
        for(let i=1;i<=this.MAX_TABLE_COUNT;i++){
            this.tables[i] = new Table(this.app, i);
            this.sortTables.push(this.tables[i]);
        }
    }

    getTable(tableId: number):Table {
        return this.tables[tableId];
    }

    private update() {
        for (let x in this.tables) {
            this.tables[x].update(100);
        }
        for(var i=0;i<this.sortTables.length;i++){
            for(var j=i+1;j<this.sortTables.length;j++){
                var t_i = this.sortTables[i];
                var t_j = this.sortTables[j];
                if(t_j.canEnter()&&t_j.getPlayerCount()>t_i.getPlayerCount()){
                    this.sortTables[i] = t_j;
                    this.sortTables[j] = t_i;
                }
            }
        }
    }

    enter(playerEnter: I_playerEnter):boolean{
        for(var i=0;i<this.sortTables.length;i++){
            var table = this.sortTables[i];
            if(table.canEnter()){
                return table.enter(new Player(playerEnter));
            }
        }
        return false;
    }

    leave(tableId: number, uid: number) {
        let table = this.getTable(tableId);
        table.leave(uid);
    }
}